import os
import json
import itertools
import copy
# from .Helper import IsInRect, IsBoxMostInRect
import myImage.Helper as Helper
# import myImage.image as utils

# import jsonpath
class JsonObject:
    def __init__(self, fileName, reOrder = False):
        self.json_data = json.load(open(fileName, 'r', encoding='utf-8'))

        [dirpath, fName] = os.path.split(fileName)
        [Name, _]        = os.path.splitext(fName)

        self.dirpath = dirpath
        self.pureName = Name

        if reOrder == True:
            self.reOrderPoints()

    def reOrderPoints(self):
        i = 0
        for shape in self.json_data['shapes']:
            i = i + 1

            label = shape['label']
            if label == 'circle':
                continue

            pts = [[], []]
            pts[0] = min(shape['points'])
            pts[1] = max(shape['points'])

            self.json_data['shapes'][i]['points'] = pts


    def getShapesInRect(self, rect, overlap):
        shapes = self.json_data['shapes']

        retShapes = []
        # print('getShapesInRect:', shapes)
        # for i in range(len(shapes)):
        #     shape = shapes[i]
        for shape in shapes:
            newShape = copy.deepcopy(shape)

            points = newShape['points']
            label  = newShape['label']

            # if abs(points[0][0] - 2064.64) < 0.1 and abs(points[0][1] - 1152.3) < 0.1:
            #     k = 0

            if label == 'circle':
                continue

            # pp = list(itertools.chain(*points))#######这里有问题

            pp = [points[0][0], points[1][0], points[0][1], points[1][1]]

            if Helper.IsInRect(pp, rect):
                points[0] = [points[0][0] - rect[0], points[0][1] - rect[1]]
                points[1] = [points[1][0] - rect[0], points[1][1] - rect[1]]
                retShapes.append(newShape)
                continue

            [bIn, inBox, ratio] = Helper.IsBoxMostInRect(pp, rect)
            if bIn == True:
                print('here:', inBox)
                points[0] = (inBox[0:3:2] - rect[0:2]).tolist()
                points[1] = (inBox[1:4:2] - rect[0:2]).tolist()

                if ratio < 0.75:
                    newShape['label'] = 'partial'

                retShapes.append(newShape)
        return retShapes



    def setAttachedData(self, box, overlap):
        self.json_data['mybox'] = box
        self.json_data['myoverlap'] = overlap

    def encodeImageData(self, img, fileName, isLowHigh):
        # [_, name, ext] = Helper.fileparts(fileName);
        print(fileName)
        [_, fName] = os.path.split(fileName)

        self.json_data['imagePath'] = fName

        img.save(fileName)
        # print(img)

        with open(fileName, 'rb') as f:
            data = f.read()

        import base64
        str = base64.b64encode(data).decode('utf-8')
        self.json_data['imageData'] = str
        # print(str)
        # self.json_data['imageData'] = utils.img_arr_to_b64(img)

    def saveJsonFile(self, fileName):
        # print(self.json_data)
        # self.json_data['imageData'] = 'str'
        # input('11111')
        import json
        with open(fileName, 'w') as f:
            json.dump(self.json_data, f, indent=2)
        # input('22222')

    def get_imagePath(self):
        return self.json_data['imagePath']

    ## 从detects中获得新的shapes
    def saveRectInBoxes(self, detects):
        shapes = self.json_data['shapes']
        retShapes = []

        labels = ['seed', 'seed_1', 'partial']
        for array in detects:
            obj = {}
            obj['label'] = labels[int(array[0])]
            obj['group_id'] = None
            obj['shape_type'] = 'rectangle'
            obj['flags'] = {}
            obj['points'] = [[array[2], array[3]], [array[4], array[5]]]
            retShapes.append(obj)

        self.json_data['shapes'] = retShapes

